import fs from 'fs/promises'
import fse from 'fs-extra'
import { dirname, resolve } from 'path'
import { fileURLToPath } from 'node:url'

const __dirname = dirname(fileURLToPath(import.meta.url))
export const rootDir = resolve(__dirname)
export const projectConfig = readProjectConfig()
export const cacheDir = resolve(rootDir, 'cache')
export const dataDir = resolve(rootDir, 'data')
export const jsonDir = resolve(dataDir, 'json')

fs.mkdir(cacheDir, { recursive: true })
fs.mkdir(dataDir, { recursive: true })

fs.mkdir(jsonDir, { recursive: true })
fs.mkdir(resolve(dataDir, 'html'), { recursive: true })

fs.mkdir(resolve(jsonDir, 'success'), { recursive: true })
fs.mkdir(resolve(jsonDir, 'fail'), { recursive: true })

function readProjectConfig() {
  const json = fse.readJsonSync('./project-config.json', { throws: false })

  return {
    'cs-eval-question': {
      start: 0,
      end: 0,
      sleep: 30,
      errors: [],
    },
    ...json,
  }
}

export const saveProjectConfig = () => {
  fse.writeJSONSync('./project-config.json', projectConfig)
}
